'use strict';
const db = uniCloud.database();
const dbCmd = db.command
const $ = db.command.aggregate
const tools = require("../../tools/index.js")
const alioss = require('../../oss/index.js')
const noticeS = require('../notice/index.js')


// 评论接口  (一级和二级一起)
exports.onCommon = async (body_data) => {
	let returnData = { code: 200,msg: "参数错误~" }
	/*
		@parentId： 一级评论回复（二级评论）所需的id
	*/
	let {articleId,UserInfo,commonValue,parentId,Second_appointed_id,reply_UseId} = body_data
	if (!articleId || !commonValue) return returnData
	
	try{
		let affair = await db.runTransaction(async transaction => {
			
			let addJson = {
				articleId,
				commonValue,
				commonTime: Date.now(),
				UserId:UserInfo._id,
				commonIp: __ctx__.CLIENTIP,
				likeList: [],
				likeCount:0
			}
			parentId ? addJson['parentId'] = parentId : ""; 												// 是否是二级评论
			Second_appointed_id && reply_UseId ? addJson['Second_appointed_id'] = Second_appointed_id : "";	// 是否是二级指定评论
			Second_appointed_id && reply_UseId ? addJson['reply_UseId'] = reply_UseId : ""; 				// 是否是二级指定评论
			
			// 添加发布信息 (只能用DB)
			let result = await db.collection('common').add(addJson)
			// 将新发布下信息返回出去
			// let NewPushRes = await transaction.collection('common').doc(result.id).get()
			let NewPushRes = await transaction.collection('common').aggregate().match({
				_id:result.id,
			}).lookup({
				from: 'User',
				localField: 'UserId',
				foreignField: '_id',
				as: "UserInfo"
			}).lookup({
				from: 'common',
				localField: '_id',
				foreignField: 'parentId',
				as: "SecondList"
			}).end()
			// 返回该用户是否点赞过  _id是数据库的用户id
			if (NewPushRes.data.length > 0 && UserInfo._id) {
				NewPushRes.data.forEach(i => {
					i.likeList.forEach(item => {
						if (item.UserId === UserInfo._id) {
							i['iSlike'] = true
						}
					})
				})
			}
			
			
			
			// 查询文章信息
			let noticeUserId = await transaction.collection('Article').where({_id:articleId}).get()
			
			// 添加通知信息
			let SelJson = {
				noticeUserId:noticeUserId.data[0].UserId,
				noticeArticleId:articleId,
				noticeCommonId:result.id,
				noticeType:2,// 评论是2
				SourceUserId:UserInfo._id
			}
			let NoticeRes = await noticeS.addNotice(SelJson)
			
			return {
				code: 200,
				msg: "评论成功~",
				data: NewPushRes.data[0]
			}
		})
		return affair
	}catch(e){
		console.log('内部错误~')
		returnData.code=500
		returnData.msg='内部错误'
		return returnData
	}
}

// 查询评论接口（一级/二级评论）
exports.SelCommonList = async (body_data) => {
	let returnData = { code: 200,msg: "参数错误~" }
	let {articleId,pageSize,pageNum,UserInfo,parentId,SortType} = body_data
	if (!articleId || !pageSize) return returnData
	let Skips = pageNum * pageSize
	
	try{
		let affair = await db.runTransaction(async transaction => {
			/*
			 排序查询配置
			*/
			let SelSortJson = {}
			if (SortType === 'SortNew' || SortType == null ) SelSortJson['commonTime'] = -1
			if (SortType === 'SortMoreLike') SelSortJson['likeCount'] = -1
			if (SortType === 'SortHot') SelSortJson['likeList'] = -1
			
			// 查询一级评论列表
			if (!parentId) {
				// 一级评论count
				let total = await transaction.collection('common').where({articleId,parentId: null}).count();
				
				// 返回评论列表信息	 |    parentId:null是找出所有的一级评论
				let result = await transaction.collection('common').aggregate().match({
					articleId,
					parentId: null
				}).sort(SelSortJson).skip(Skips).limit(pageSize).lookup({
					from: 'User',
					localField: 'UserId',
					foreignField: '_id',
					as: "UserInfo"
				}).lookup({
					from: 'common',
					localField: '_id',
					foreignField: 'parentId',
					as: "SecondList"
				}).end()
				// 返回该用户是否点赞过  _id是数据库的用户id
				if (result.data.length > 0 && UserInfo._id) {
					result.data.forEach(i => {
						i.likeList.forEach(item => {
							if (item.UserId === UserInfo._id) {
								i['iSlike'] = true
							}
						})
					})
				}
				return {
					code: 200,
					msg: "查询评论成功~",
					data: result.data,
					total: total.total
				}
			
			
			
			
			// 查询二级评论列表
			} else { 
				
				// 查总数
				let total = await transaction.collection('common').where({articleId,parentId}).count();
				
				// 先查楼主信息
				let FirstCommon = await transaction.collection('common').aggregate().match({
					_id: parentId
				}).lookup({
					from: 'User',
					localField: 'UserId',
					foreignField: '_id',
					as: "UserInfo"
				}).sort({
					commonTime: -1
				}).end()
				
				// 楼主信息不存在
				if(FirstCommon.data.length===0){
					return {code: 200,msg: "该评论已被删除~"}
				}
				
				// 返回该用户是否点赞过 虽然数据只有一条，但是是直接复制过来懒得改
				FirstCommon.data.forEach(i => {
					i.likeList.forEach(item => {
						if (item.UserId === UserInfo._id) {
							i['iSlike'] = true
						}
					})
				})
		
		
				// 再查二级评论
				let SecondCommon = await db.collection('common').aggregate().match({
					parentId
				}).sort({
					commonTime: -1
				}).skip(Skips).limit(pageSize).lookup({
					from: 'User',
					localField: 'UserId',
					foreignField: '_id',
					as: "UserInfo"
				}).lookup({
					from: 'User',
					localField: 'reply_UseId',
					foreignField: '_id',
					as: "ReplyToUserInfo"
				}).end()
				// 返回该用户是否点赞过
				if (SecondCommon.data.length > 0 && UserInfo._id) {
					SecondCommon.data.forEach(i => {
						i.likeList.forEach(item => {
							if (item.UserId === UserInfo._id) {
								i['iSlike'] = true
							}
						})
					})
				}
				FirstCommon.data[0]['SecondList'] = SecondCommon.data
				return {
					code: 200,
					msg: "查询评论成功~",
					data: FirstCommon.data[0],
					total: total.total
				}
			}
		})
		return affair
	}catch(e){
		console.log('内部错误~')
		returnData.code=500
		returnData.msg='内部错误'
		return returnData
	}
}

// 单条评论点赞
exports.CommonLike = async (body_data) => {
	let returnData = { code: 200,msg: "参数错误~" }
	let {_id,UserInfo} = body_data
	if (!_id) return returnData

	try{
		let affair = await db.runTransaction(async transaction => {
			//  查询是否点赞过
			let IsLike = await transaction.collection('common').aggregate().match({
				_id
			}).project({
				likeList: $.filter({
					input: '$likeList',
					as: 'item',
					cond: $.eq(['$$item.UserId', UserInfo._id])
				})
			})
			
			
			.end()
			// 已点赞过 取消点赞
			if (IsLike.data[0].likeList.length > 0) {
				// return {code: 200,msg: "您已点赞过~",iSlike: true}
				const res = await transaction.collection('common').where({_id}).get() // 取数据
				
				if(res.data.length>0){
					let index = res.data[0].likeList.findIndex((i)=>i.UserId===UserInfo._id) // 取likeList中该用户点赞信息的下标
					res.data[0].likeList.splice(index,1)	// 切割
					let result = await transaction.collection('common').doc(_id).update({
						likeList: res.data[0].likeList,
						likeCount:res.data[0].likeList.length
					}) // 刷新
					if(result.updated>0){
						return {
							code: 200,
							msg: "点赞取消成功~",
							iSlike: false
						}
					}else{
						return {code:204,msg:"更新未成功~"}
					}
				
				}else{
					return {code:204,msg:"请求超时1"}
				}
				
			 // 未点赞过
			} else {
				
				// 更新数据中的likeList插入数据
				let result = await transaction.collection('common').doc(_id).update({
					likeList: dbCmd.push([{
						UserId:UserInfo._id,
						UpdateTime: Date.now(),
						Ip: __ctx__.CLIENTIP
					}]),
					likeCount:dbCmd.inc(1)
				})
				
				// 添加通知信息
				let SelJson = {
					noticeUserId:IsLike.data[0].UserId,
					noticeArticleId:_id,
					noticeCommonId:result._id,
					noticeType:7,	
					SourceUserId:UserInfo._id
				}
				let NoticeRes = await noticeS.addNotice(SelJson)
				
				return {
					code: 200,
					msg: "点赞成功~",
					iSlike: true,
					data: result,
					NoticeRes:NoticeRes
				}
				
			}
		})
		return affair
	}catch(e){
		console.log('内部错误~')
		returnData.code=500
		returnData.msg='内部错误'
		return returnData
	}
}

// 评论排序（已经废弃）
exports.CommonSort = async (body_data) => {
	let {
		SortType,
		articleId,
		pageSize,
		pageNum,
		UserId
	} = body_data
	if (!SortType || !articleId) return {
		code: 200,
		msg: "参数错误~"
	}
	let Skips = pageNum * pageSize
	let total = await db.collection('common').where({
		articleId,
		parentId: null
	}).count()

	let SelSortJson = {}
	if (SortType === 'SortNew') SelSortJson['commonTime'] = -1
	if (SortType === 'SortMoreLike') SelSortJson['likeCount'] = -1
	if (SortType === 'SortHot') SelSortJson['likeList'] = -1


	// 返回评论列表信息	 // parentId:null是找出所有的一级评论
	let result = await db.collection('common').aggregate().match({
		articleId,
		parentId: null
	}).sort(SelSortJson).skip(Skips).limit(pageSize).lookup({
		from: 'User',
		localField: 'UserId',
		foreignField: '_id',
		as: "UserInfo"
	}).lookup({
		from: 'common',
		localField: '_id',
		foreignField: 'parentId',
		as: "SecondList"
	}).end()
	// 过滤添加 iSlike字段
	if (result.data.length > 0 && UserId) {
		result.data.forEach(i => {
			i.likeList.forEach(item => {
				if (item.UserId === UserId) {
					i['iSlike'] = true
				}
			})
		})
	}

	// 排序最多点赞   垃圾排序 冒泡
	// if (result.data.length > 0 && UserId && SortType === 'SortMoreLike') {
	// 	for (let j = 0; j < result.data.length - 1; j++) {
	// 		for (let i = 0; i < result.data.length - 1 - j; i++) {
	// 			if (result.data[i].likeList.length < result.data[i + 1].likeList.length) {
	// 				let temp = result.data[i];
	// 				result.data[i] = result.data[i + 1];
	// 				result.data[i + 1] = temp;
	// 			}
	// 		}
	// 	}
	// }


	return {
		code: 200,
		msg: "查询评论成功~",
		data: result.data,
		total: total.total
	}

}